<?php

use Core\AdminController;
use Models\Supplier;

class SupplierController extends AdminController
{
	public function index()
	{
		$query = Supplier::select('*');

		$suppliers = $query->paginate(20);

		$this->load->view('admin/supplier/index', [
			'suppliers' => $suppliers
		]);	
	}

	public function save($id = null)
	{
		$supplier = $id ? (new Supplier)->find($id) : (new Supplier);

		if (!$supplier) {
			return $this->response([], 404);
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', '名称', 'required')
			->set_rules('address', '地址', 'required')
			->set_rules('tel', '电话', 'required|numeric')
			->set_rules('name', '联系人', 'required');
		if (!$this->form_validation->run()) {
			return $this->response([
				'error' => $this->form_validation->error_string(),
			], 422);
		}

		$supplier->load($this->input->post(null, true));
		if ($id) {
			$supplier->update();	
		} else {
			$supplier['create_time'] = date('Y-m-d H:i:s');
			$supplier->add();
		}

		return $this->response($supplier->toArray());
	}

	public function delete($id)
	{
		$supplier = (new Supplier)->find($id);

		if (!$supplier) {
			return $this->response([], 404);
		}

		$supplier->delete();

		return $this->response();
	}
}